package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.constants.WxPayConstants;
import com.example.domain.Order;
import com.example.dto.WxChatBasePayDto;
import com.example.dto.WxChatCallbackRefundDto;
import com.example.dto.WxChatPayDto;
import com.example.service.WechatRefundCallback;
import com.example.service.WxOrderService;
import com.example.utils.Result;
import com.example.utils.WxPayRefundCallbackUtil;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@RestController
@RequestMapping("/wx/order")
@Api(tags = "微信 - 用户订单管理")
public class WxOrderController {

    @Resource
    private WxOrderService wxOrderService;
    @Resource
    private WxPayConstants wxPayConfig;
    @Resource
    private Verifier verifier;

    @PostMapping("/addWxOrder")
    @ApiOperation("生成订单并支付")
    public Result addWxOrder(@RequestBody Order runOrder){
        return wxOrderService.addWxOrder(runOrder);
    }

    @PostMapping("/pay")
    @ApiOperation("微信用户调用微信支付")
    public WxChatPayDto pay(WxChatBasePayDto payData){
        return wxOrderService.pay(payData);
    }

    @RequestMapping("/wxOrderCallBack")
    @ApiOperation("订单支付后回调")
    public Map<String, String> wxOrderCallBack(HttpServletRequest request, HttpServletResponse response){
        return wxOrderService.wxOrderCallBack(request,response);
    }

    @GetMapping("/orderRefund")
    @ApiOperation("订单退款，拼接订单id(?id)")
    public Result orderRefund(Integer id){
        return wxOrderService.orderRefund(id);
    }

    @ApiOperation("微信退款回调接口")
    @PostMapping("/refundWechatCallback")
    public String refundWechatCallback(HttpServletRequest request, HttpServletResponse response) {
        return WxPayRefundCallbackUtil.wxPayRefundCallback(request, response, verifier, wxPayConfig, new WechatRefundCallback() {
            @Override
            public void success(WxChatCallbackRefundDto refundData) {
                // TODO 退款成功的业务逻辑，例如更改订单状态为退款成功等
                Order one = wxOrderService.getOne(new QueryWrapper<Order>()
                        .eq("order_number", refundData.getOrderId()));
                one.setOrderStatus(4);
                wxOrderService.updateById(one);
            }

            @Override
            public void fail(WxChatCallbackRefundDto refundData) {
                // TODO 特殊情况下退款失败业务处理，例如银行卡冻结需要人工退款，此时可以邮件或短信提醒管理员，并携带退款单号等关键信息
                System.out.println("退款失败");
            }
        });
    }

}
